package web;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import objects.Board;
import objects.BoardData;
import objects.Character;
import objects.ConfigurationType;
import objects.Player;
import utils.AutoDealer;
import utils.FileHandler;
import utils.PlayerFactory;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

/**
 * Servlet implementation class CreateGame
 */

@WebServlet(name = "CreateGame", urlPatterns = {"/CreateGame"})
public class CreateGameServlet extends HttpServlet 
{
	//Inner class used to deserialize json into info
	private class PlayerJSON 
	{
	    private String name;
	    private String playerType;
	}    
	
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public CreateGameServlet() {
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		if (Board.getInstance().isManualError())
		{
			request.setAttribute("pageName", "errorPage"); 
	    	// Call index.jsp (the page to call was set by pageName on the jsp)
	    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
	    	dispatcher.forward(request, response);
		}
		else
		{
		 request.setAttribute("pageName", "game"); 
		 try
		 {
			 request.setAttribute("playerID", Board.getInstance().getCurrPlayerInstance().getPlayerName());
		 }
		 catch (Exception e)
		 {
			 
		 }
		 // Call index.jsp (the page to call was set by pageName on the jsp)

	    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
	    	dispatcher.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		if (Board.getInstance().isGameInitialized() || Board.getInstance().isGameStarted())
		{
	    	Board.getInstance().setManualError(true);
	    	return;
		}
		
		Board.getInstance().setManualError(false);
		
		Board.getInstance().resetInstance();
			
		// Collect number of players and build game configuration class
        String numOfPlayersAsString = request.getParameter("numOfPlayers");
        
        // Create new board data
        BoardData bdToAdd = new BoardData();
		List<Player> lstPlayers = new ArrayList<Player>();
		
		Player plNew = null;
		
		// Create a player for the maker of the game
		plNew=PlayerFactory.createPlayer(1, request.getParameter("playerName"), Character.values()[0], "HUMAN", 1);
		
		lstPlayers.add(plNew);
		
		JsonObject jsAction = new JsonObject();
		jsAction.addProperty("code", "join");
		jsAction.addProperty("player", plNew.getPlayerName());
		
		
		jsAction.addProperty("message", "Player " +plNew.getPlayerName()+ " has joined the game!");
		Board.getInstance().addJsActions(jsAction);
		
		int numOfComputerPlayers = Integer.valueOf(request.getParameter("numOfComputerPlayers"));
		
		// Create players according to the configurations defined by the maker of the game
		for (int i = 1; i < Integer.valueOf(numOfPlayersAsString); i++) {
           
           if (i <= numOfComputerPlayers)
           {
        	   plNew=PlayerFactory.createPlayer(i+1, "comp" + i, Character.values()[i], "COMPUTER", i+1);
           }
           else
           {
        	   plNew=PlayerFactory.createPlayer(i+1, "human" + i, Character.values()[i], "HUMAN", i+1);
           }
           
           lstPlayers.add(plNew);
           
        }
        
		// Set the number of players that have joined to be the maker + all the ai players
		Board.getInstance().setNumberOfPlayersJoined(numOfComputerPlayers + 1);
		Board.getInstance().setNumberOfPlayersTotal(Integer.valueOf(numOfPlayersAsString));
		
		if (Board.getInstance().isGameStarted())
		{
			jsAction.addProperty("waitformore", 0);
		}
		else
		{
			jsAction.addProperty("waitformore", 1);
		}
		
    	bdToAdd.setPlayers(lstPlayers);
    	
    	// Deal the cards
        bdToAdd = AutoDealer.Deal(bdToAdd);
        bdToAdd.setType(ConfigurationType.MANUAL);
        Board.getInstance().setBdGameData(bdToAdd);
        Board bd = Board.getInstance();
    	
        for (Player player : bd.getBdGameData().getPlayers()) 
    	{
			// Enter the player to the room number roomNumber
			Board.getInstance().getRooms()[0].participantEnter(player);
			player.setRoomNumber(0);
		}

    	Board.getInstance().backUp();
	}
}
